package com.zhouyu.mysql.core;

import com.zhouyu.mysql.dict.DictColumn;
import com.zhouyu.mysql.dict.DictTable;
import com.zhouyu.mysql.dict.SystemDict;
import com.zhouyu.mysql.page.IndexPage;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.select.FromItemVisitorAdapter;
import net.sf.jsqlparser.statement.select.PlainSelect;

import java.util.Optional;

import static com.zhouyu.mysql.page.IndexPage.PAGE_NEW_INFIMUM;

/**
 * 大都督周瑜（我的微信: dadudu6789）
 */
public class DTupleUtil {

    public static DTuple convert(Insert insertStatement) {
        DTuple dTuple = new DTuple();

        String tableName = insertStatement.getTable().getName();
        ExpressionList<Column> columns = insertStatement.getColumns();
        ExpressionList<?> values = insertStatement.getValues().getExpressions();

        for (int i = 0; i < columns.size(); i++) {
            Column column = columns.get(i);
            Expression value = values.get(i);

            DictTable dictTable = SystemDict.getInstance().getNameTables().get(tableName);
            Optional<DictColumn> dictColumn = dictTable.getDictColumnList().stream().filter(c -> c.getName().equals(column.getColumnName())).findFirst();
            if (dictColumn.isPresent()) {
                DField dField = new DField();
                dField.setDictColumn(dictColumn.get());

                if (!(value instanceof NullValue)) {
                    if (dictColumn.get().isInt()) {
                        dField.setData(Integer.valueOf(value.toString()));
                    } else {
                        dField.setData(((StringValue) value).getValue());
                    }
                } else {
                    // 如果插入的是NULL，则用两个00表示
                    dField.setData("00");
                }

                dTuple.getFields().add(dField);
            } else {
                throw new RuntimeException(String.format("%s字段不存在", column.getColumnName()));
            }
        }

        return dTuple;
    }

    public static DTuple convert(PlainSelect selectStatement) {
        // 获取表名
        final String[] tableNameArray = new String[1];
        selectStatement.getFromItem().accept(new FromItemVisitorAdapter() {
            @Override
            public void visit(Table table) {
                tableNameArray[0] = table.getName();
            }
        });
        String tableName = tableNameArray[0];

        DTuple dTuple = new DTuple();

        Expression where = selectStatement.getWhere();
        if (where instanceof EqualsTo equalsToWhere) {
            Column leftExpression = (Column) equalsToWhere.getLeftExpression();

            DictTable dictTable = SystemDict.getInstance().getNameTables().get(tableName);
            Optional<DictColumn> dictColumn = dictTable.getDictColumnList().stream().filter(c -> c.getName().equals(leftExpression.getColumnName())).findFirst();

            if (dictColumn.isPresent()) {
                DField dField = new DField();
                dField.setDictColumn(dictColumn.get());
                if (dictColumn.get().isInt()) {
                    LongValue rightExpression = (LongValue) equalsToWhere.getRightExpression();
                    dField.setData(Integer.valueOf(rightExpression.getStringValue()));
                } else {
                    StringValue rightExpression = (StringValue) equalsToWhere.getRightExpression();
                    dField.setData(rightExpression.getValue());
                }
                dTuple.getFields().add(dField);
            }
        }

        return dTuple;
    }

    public static DTuple generateIndexRecord(IndexPage indexPage) {
        DTuple dTuple = new DTuple();

        // 获取第一条记录的主键id
        int recId = RecUtil.getRecId(indexPage, indexPage.rec_get_next_offs(PAGE_NEW_INFIMUM));

        DictColumn idDictColumn = new DictColumn();
        idDictColumn.setName("id");
        idDictColumn.setType("int");
        idDictColumn.setLen(4);

        DField idField = new DField();
        idField.setData(recId);
        idField.setDictColumn(idDictColumn);

        DictColumn pageNoDictColumn = new DictColumn();
        pageNoDictColumn.setName("pageNo");
        pageNoDictColumn.setType("int");
        pageNoDictColumn.setLen(4);

        DField pageNoField = new DField();
        pageNoField.setData(indexPage.fil_page_get_page_offset());
        pageNoField.setDictColumn(pageNoDictColumn);

        dTuple.getFields().add(idField);
        dTuple.getFields().add(pageNoField);

        return dTuple;
    }
}
